package br.com.ctm.advogadope.rest.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.PersistenceException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;

import br.com.ctm.advogadope.model.Processo;
import br.com.ctm.advogadope.model.Tribunal;
import br.com.ctm.advogadope.model.Tribunal.TipoJuizo;
import br.com.ctm.advogadope.model.Usuario;
import br.com.ctm.advogadope.negocio.api.ProcessoNegocio;
import br.com.ctm.advogadope.negocio.api.UsuarioNegocio;
import br.com.ctm.advogadope.rest.api.ProcessoJudicialResource;
import br.com.ctm.advogadope.rest.entity.ProcessoDTO;
import br.com.framework.negocio.exception.NegocioException;
import br.jus.cnj.intercomunicacao.beans.ProcessoJudicial;

/**
 * @author Cleber
 * 
 */
@Path("processosJudiciais")
@Named
public class ProcessoJudicialResourceImpl extends
		EntityResourceImpl<Processo, ProcessoNegocio> implements
		ProcessoJudicialResource {

	@Inject
	private UsuarioNegocio usuarioNegocio;

	@Inject
	private ProcessoNegocio processoNegocio;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ctm.advogadope.rest.api.EntityResourceImpl#setNegocio(br.com.framework
	 * .negocio.api.BaseNegocio)
	 */
	@Override
	@Inject
	protected void setNegocio(ProcessoNegocio negocio) {
		super.setNegocio(negocio);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ctm.advogadope.rest.api.EntityResource#findByID(java.lang.Long)
	 */
	@Override
	@GET
	@Path("{id}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Processo findByID(@PathParam("id") Long id)
			throws PersistenceException {
		return super.findByID(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ctm.advogadope.rest.api.EntityResource#findAll()
	 */
	@Override
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public List<Processo> findAll() throws PersistenceException {
		return super.findAll();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ctm.advogadope.rest.api.EntityResource#findAll(int, int)
	 */
	@Override
	@GET
	@Path("paginated/{firstResult}/{maxResults}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public List<Processo> findAll(@PathParam("firstResult") int firstResult,
			@PathParam("maxResults") int maxResults)
			throws PersistenceException {
		return super.findAll(firstResult, maxResults);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ctm.advogadope.rest.api.EntityResource#findByExample(br.com.framework
	 * .persistencia.model.BaseEntity)
	 */
	@Override
	@GET
	@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public List<Processo> findByExample(Processo entidade)
			throws PersistenceException {
		return super.findByExample(entidade);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ctm.advogadope.rest.api.EntityResource#getRecordCount()
	 */
	@Override
	@GET
	@Path("count")
	@Produces(MediaType.TEXT_PLAIN)
	public Long getRecordCount() throws PersistenceException {
		return super.getRecordCount();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.com.ctm.advogadope.rest.api.EntityResource#insert(br.com.framework
	 * .persistencia.model.BaseEntity)
	 */
	@Override
	@POST
	@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response insert(Processo entidade) throws NegocioException,
			PersistenceException {
		return super.insert(entidade);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ctm.advogadope.rest.api.EntityResource#update(java.lang.Long,
	 * br.com.framework.persistencia.model.BaseEntity)
	 */
	@Override
	@PUT
	@Path("{id}")
	@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Response update(@PathParam("id") Long id, Processo entidade)
			throws NegocioException, PersistenceException {
		return super.update(id, entidade);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.com.ctm.advogadope.rest.api.EntityResource#remove(java.lang.Long)
	 */
	@Override
	@DELETE
	@Path("{id}")
	public Response remove(@PathParam("id") Long id) throws NegocioException,
			PersistenceException {
		return super.remove(id);
	}

	@Override
	@POST
	@Path("cliente/pje")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public List<ProcessoDTO> findProcessoJudicialByCliente(
			@FormParam("email") String email,
			@FormParam("firstResult") @DefaultValue("-1") int firstResult,
			@FormParam("maxResults") @DefaultValue("-1") int maxResults) {
		Usuario usuario = new Usuario();
		usuario.setEmail(email);
		List<Usuario> list = usuarioNegocio.findByExample(usuario);
		List<Processo> processos = new ArrayList<Processo>();
		if (!list.isEmpty()) {
			usuario = list.get(0);
			processos = processoNegocio.findByAdvogado(usuario.getAdvogado(),
					firstResult, maxResults, true);
		}
		List<ProcessoDTO> resultList = new ArrayList<ProcessoDTO>();
		for (Processo p : processos) {
			ProcessoJudicial processoJudicial = null;
			try {
				processoJudicial = processoNegocio.buscarProcessoJudicial(p, true, null);
			} catch (Exception e) {
				LOGGER.error("Nao foi possivel consultar processo judicial", e);
			}
			if (processoJudicial != null) {
				ProcessoDTO processoDTO = new ProcessoDTO(processoJudicial);
				processoDTO.setTipoJuizo(p.getTipoJuizo());
				processoDTO.setTribunal(p.getTribunal());
				resultList.add(processoDTO);
			}
		}
		return resultList;
	}

	@Override
	@POST
	@Path("cliente/pje/porTribunal")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public List<ProcessoDTO> findProcessoJudicialByTribunalETipoJuizo(
			@FormParam("idTribunal") Long idTribunal, @FormParam("tipoJuizo") String tipoJuizo) {
		Tribunal trib = new Tribunal();
		trib.setId(idTribunal);
		Processo pEx = new Processo();
		pEx.setTribunal(trib);
		pEx.setTipoJuizo(TipoJuizo.valueOf(tipoJuizo));
		List<Processo> processos = processoNegocio.findByExample(pEx);
		List<ProcessoDTO> resultList = new ArrayList<ProcessoDTO>();
		for (Processo p : processos) {
			ProcessoJudicial processoJudicial = null;
			try {
				processoJudicial = processoNegocio.buscarProcessoJudicial(p, true, null);
			} catch (Exception e) {
				LOGGER.error("Nao foi possivel consultar processo judicial", e);
			}
			if (processoJudicial != null) {
				ProcessoDTO processoDTO = new ProcessoDTO(processoJudicial);
				processoDTO.setTipoJuizo(p.getTipoJuizo());
				processoDTO.setTribunal(p.getTribunal());
				resultList.add(processoDTO);
			}
		}
		return resultList;
	}
	
	@Override
	@POST
	@Path("cliente/pje/porTribunaleNPU")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	@Wrapped(element = "processos")
	public ProcessoDTO findProcessoJudicialByTribunalTipoJuizoENpu(
			@FormParam("idTribunal") Long idTribunal, @FormParam("tipoJuizo") String tipoJuizo, String npu) {
		
		Tribunal trib = new Tribunal();
		trib.setId(idTribunal);
		Processo pEx = new Processo();
		pEx.setTribunal(trib);
		pEx.setTipoJuizo(TipoJuizo.valueOf(tipoJuizo));
		List<Processo> processos = processoNegocio.findByExample(pEx);
		
		ProcessoDTO processoDTO = new ProcessoDTO();
		
		
		return processoDTO;
		
	}

	@Override
	public Processo consultarProcesso(String npu, Long idTribunal,
			String tipoJuizo) {
		// TODO Auto-generated method stub
		return null;
	}

}
